# -*- coding: utf-8 -*-
import sys
import pymongo
from config import  MONGODB_CONFIG
import Util
import random
from Util import getDict
SCHEME_TAG_LIST_COLL=[("tag_list_id",int),("tag_id",int),("ans",int),("ace",int)]
SCHEME_PIC_USER_COLL=[("uid",int),("pid",int),("tag_list",int)]
SCHEME_TAG_PIC_COLL = [("tag", str), ("pid", int), ("yesNum", int), ("noNum", int)]
SCHEME_PIC_COLL = [("pid", int), ("pic", str)]
SCHEME_TAG_COLL = [("tag_id", int), ("tag", str)]
SCHEME_UID_PID_TID_ANS_ACE_COLL=[("uid",int),("pid",int),("tid",int),("ans",int),("ace",int)]
'''
-------mongoDB collection Design------
#pid: 9999(sample_id)99999(pid) uid:user_id tid:tag_id true_tid:the actual tag id(judged by algorithm)
#yes_num:the num of "yes" for a question

uid_pid_tid_ans_ase_coll
{"uid":1,"pid":100000001,"tid":1,"ans":1,"ase":0}
tid_pid_num_coll
{"tid":1,"pid":100000001,"yes_num":10,"no_num":11}
pid_truetid_coll
{"pid":100000001,"true_tid":1}
tag_tid_coll
{"tag":"isPlane","tid":1}
pic_pid_coll
{"pic":"Plane","pid":100000001}
'''
class MongoDBBase(object):
    def __init__(self,host=MONGODB_CONFIG['host'],port=MONGODB_CONFIG['port'],
    dbname='test',username=MONGODB_CONFIG['username'],password=MONGODB_CONFIG['password']):
        try:
            self._conn=pymongo.MongoClient(host,port)
            self._db=self._conn[dbname]
            self._username=username
            self._password=password
            '''
            authenticated = self._db.authenticated(self._username, self._password)
            if  authenticated is False:
                raise Exception("Authenticate failed!")
            '''
        except Exception:
            print ('Connect statics fail')
            sys.exit(1)
        print("######DB: %s connect successfully!"%dbname)
    def close(self):
        self._conn.close()
    def get_coll(self,collname):
        coll=self._db[collname]
        if coll:
            #print ('Coll: %s is found'%collname)
            return coll
        else:
            print ('Coll: %s not found'%collname)
            return None
    def insertDoc(self,collname,scheme,data_set):
        #param data_set: {"name":"liuzeduo","count":11,"age":17 }
        #param scheme:[("tag_list_id",int),("tag_id",int),("ans",int),("ace",int)]
        new_doc={}
        for field in scheme:
            fieldname=field[0]
            fieldtype=field[1]
            try:
                if data_set[fieldname] is not None and type(data_set[fieldname]) == fieldtype:
                    #print("fieldname: %s value: %s"%(fieldname,data_set[fieldname]))
                    new_doc[fieldname]=data_set[fieldname]
                else:
                    raise Exception("Wrong with the field:%s"%fieldname)
            except:
                pass
        coll=self.getColl(collname)
        result=coll.insert_one(new_doc)
        print("######insert: \n%s"%(result))
        return result
    def insert_doc(self,coll,doc):
        result = coll.insert_one(doc)
        #print("######insert: \n%s" % (result))
        return result
    def get_doc(self,coll,doc_filter):
        #param doc_filter {"age": {"$lt": 15}}
        result_list=coll.find(doc_filter)
        doc_list=[]
        for u in result_list:
            doc_list.append(u)
        return doc_list
    def update_doc(self,coll,doc_filter,new_doc,field_update_list):
        doc = coll.find_one(doc_filter)
        if doc is None:
            print("######doc not exist!need to insert")
            self.insert_doc(coll,new_doc)
        else:
            print("######doc exist!need to update")
            for field in field_update_list:
                doc[field]=new_doc[field]
            coll.save(doc)


if __name__ == '__main__':
    myconn=MongoDBBase()


    coll=myconn.get_coll("uid_pid_tid_ans_ase_coll")
    for uid in range(10):
        for pid in range(20):
            for tid in range(4):
                doc=Util.getDict(
                    uid=uid + 1, pid=100000001 + pid , tid=tid+1, ans=random.choice([-1, 0, 1]), ase=0)
                coll.insert_one(doc)

    coll = myconn.get_coll("tid_pid_num_coll")
    for pid in range(10):
        for tid in range(20):
            doc=Util.getDict(
                pid=100000001 + pid , tid=tid+1, yes_num=random.choice(range(20)), no_num=random.choice(range(20)))
            coll.insert_one(doc)

    myconn.get_doc(coll=coll,doc_filter={"ans":1})
    myconn.update_doc(coll=coll,doc_filter={"uid":2,"pid":100000002},new_doc={"uid":2,"pid":100000002,"tid":2,"ans":0,"ase":1},field_list=["ase"])